/**
 * 
 */
package org.metaverse.h2;

import java.io.IOException;
import java.util.Iterator;

import org.metaverse.warehouse.Senary;
import org.singularity.io.CloseableIterator;

/**
 * @author vjache
 *
 */
public class SenaryPagedIterator implements CloseableIterator<Senary> {

	private final CloseableIterator<Iterator<Senary>> _pagedReader;
	private Iterator<Senary> _page;
	private Senary _nextSenary;

	/**
	 * 
	 */
	public SenaryPagedIterator(CloseableIterator<Iterator<Senary>> aPagedReader) {
		_pagedReader = aPagedReader;
		advance();
	}
	
	private void advance() {
		if(_page==null || !_page.hasNext())
		{
			//Try read next page
			if(_pagedReader.hasNext())
			{
				_page = _pagedReader.next();
				advance();
			}
			else
				_nextSenary = null;
		}
		else// Page not null and has next
			_nextSenary = _page.next();
	}

	/* (non-Javadoc)
	 * @see java.io.Closeable#close()
	 */
	@Override
	public void close() throws IOException {
		_pagedReader.close();
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#hasNext()
	 */
	@Override
	public boolean hasNext() {
		return _nextSenary!=null;
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#next()
	 */
	@Override
	public Senary next() {
		final Senary ret = _nextSenary;
		advance();
		return ret;
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#remove()
	 */
	@Override
	public void remove() {throw new UnsupportedOperationException();}

}
